"use strict";

var C = require('../lib/common');

module.exports = function (engine, attributes, content, next) {

    var dbKey = engine.parseValue(attributes.db);
    content = JSON.parse(content);

    C.H.connectDb(dbKey, function (err, db) {
        if (err) throw err;

        C.async.each(C._.keys(content), function (cName, cb1) {
            var records = content[cName];
            C._.isArray(records) || (records = [records]);

            var coll = db.collection(cName);

            C.async.eachSeries(records, function (r, cb2) {

                coll.insert(r, { safe: true }, function (err) {
                    if (err) return cb2(err);

                    console.log('Inserted a doc ' + JSON.stringify(r) + ' on collection [' + cName + '].');

                    cb2();
                });

            }, function (err) {
                if (err) return cb1(err);

                cb1();
            });
        }, function (err) {
            if (err) return next(err);

            next();
        });
    });
};